package com.atguigu.flink.chapter11.function;

import com.atguigu.flink.bean.WaterSensor;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.ScalarFunction;

/**
 * @Author lzc
 * @Date 2022/7/13 13:57
 */
public class Flink01_Scalar {
    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
    
        DataStreamSource<WaterSensor> stream = env.fromElements(
            new WaterSensor("sensor_1", 1L, 10),
            new WaterSensor("sensor_1", 2L, 20),
            new WaterSensor("sensor_2", 3L, 30),
            new WaterSensor("sensor_1", 4L, 40),
            new WaterSensor("sensor_2", 5L, 50),
            new WaterSensor("sensor_1", 6L, 60)
        );
    
    
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
    
        Table table = tEnv.fromDataStream(stream);  // 把流转成一个动态表
        tEnv.createTemporaryView("sensor", table);
        
        
        // 1. 在tableApi中使用
        
        // 1.1 内联的方式使用
        /*table
            .select($("id"), call(MyUpper.class, $("id")).as("id_upper"))
            .execute()
            .print();*/
        
        // 1.2 先注册后使用
        tEnv.createTemporaryFunction("my_upper", MyUpper.class);
        /*table
            .select($("id"), call("my_upper", $("id")).as("id_upper"))
            .execute()
            .print();*/
        
        
        // 2. 在sql中使用
        tEnv.sqlQuery("select " +
                          " id, " +
                          " my_upper(id, vc) upper_id " +
                          "from sensor")
            .execute()
            .print();
        
        
    }
    
    
    public static class MyUpper extends ScalarFunction {
        // 约定好的方法要实现
        // 1. 返回值根据实际定
        // 2. 方法名: 必须是eval
        // 3. 参数根据实际定
        public String eval(String s, Integer a){
            if (s == null) {
                return null;
            }
            return s.toUpperCase() + a;
        }
    }
}
